//点击搜集
function clickCollect(keyword, filterStr, recBatchId, categoryId, productId, channelSource){
	console.log("onSearchListClick参数:productId=" + productId + ";categoryId=" + categoryId 
			+ ";recBatchId=" + recBatchId + ";channelSource=" + channelSource
			+ ";keyword=" + keyword + ";filterStr=" + filterStr
			);
	if(productId!=''){
 		$.ajax({
			url : "http://s.lvmama.com/ajax/onSearchListClick.do",
			type : "post",
			dataType:"json",
			async: true,
			data : {'productId':productId,'filterStr':filterStr,'keyword':keyword,
				'recBatchId':recBatchId,'categoryId':categoryId,'channelSource':channelSource},
			success : function(result) {
				if(result=="SUCCESS"){
					console.log("onSearchListClick 成功");
				}else {
					console.log("onSearchListClick 失败");
				}
			}
		});
 	}
}

//触发曝光
var exposuredProductIndex={};
function onProductExposure(currentIndex,keyword,filterStr){
	try{
		if(currentIndex>=0&&currentIndex<=exposuredProductList.length&&!exposuredProductIndex[currentIndex]){
			var item=exposuredProductList[currentIndex];
			var productId=item["productId"];
			var recBatchId=item["recBatchId"];
			var categoryId=item["categoryId"];
			var channelSource=item["channelSource"];
			console.log("onSearchListExposure参数:productId=" + productId + ";categoryId=" + categoryId 
					+ ";recBatchId=" + recBatchId + ";channelSource=" + channelSource
					+ ";keyword=" + keyword + ";filterStr=" + filterStr
					);
			exposuredProductIndex[currentIndex]="1";
			$.ajax({
				url : "http://s.lvmama.com/ajax/onSearchListExposure.do",
				type : "post",
				dataType:"json",
				async: true,
				data : {'productId':productId,'filterStr':filterStr,'keyword':keyword,'recBatchId':recBatchId,'categoryId':categoryId,'channelSource':channelSource},
				success : function(result) {
					if(result=="SUCCESS"){
						console.log("onSearchListExposure 成功");
					}else {
						console.log("onSearchListExposure 失败");
					}
				}
			});
		}
	}catch(e){
		console.log("error "+e);
	}
}

$(function(){
	
	   //神策埋点  刷新发送事件
	   sendSensorsDataForRefresh();
	
	
	   var $doc = $(document),
	   $win = $(window),
	   $prdLi = $('.product-item,.prdLi');

	   //曝光获取显示的列
	   function exposure() {
	       var minTop = $doc.scrollTop(), 
	       maxTop = minTop + $win.height();
	       $prdLi.each(function(index, el) {
	           var $this = $(this),
	           thisTop = $this.offset().top  + ($this.outerHeight()/2);
	           if ( maxTop > thisTop && $this.attr('exposure') !== 'exped' && $this.offset().top > minTop ) {
	               //标记已曝光
	               $this.attr('exposure', 'exped');

	               //逐条曝光
	               //console.log(index,$this,el);
	               onProductExposure(index,exposuredKeyword,exposuredFilterStr);
	           }
	       });
	   }       

	   //页面滚动执行
	   $win.scroll(function(event) {
	       exposure();
	   });

	   // 默认进页面执行一行
	   exposure();
});

//神策收集数据
function gatherInfoBySensors(name,params){
	//alert(JSON.stringify(params));
	try{
		sensors.track(name, params);
	}catch(e){
		
		console.log("error "+e);
	}
}
//酒店点击搜索产品(完成)
function  hotelSearchResultClick(current_page,search_tab_name,destination,search_keyword,date_checkin,date_checkout,product_id,product_name,search_position_index,is_ad,ad_source){
	if(is_ad!=null && is_ad!=''){
		is_ad=true;
		if('1'==ad_source){
			ad_source="大数据推荐（优选标签）";
		}else if('2'==ad_source){
			ad_source="后台配置（推荐标签）";
		}
		
	}else{
		is_ad=false;
	}
	
	current_page='搜索列表';
	search_tab_name='酒店';
	destination = $("#js_destination").val();
	if('酒店名/商圈/地标'==search_keyword){
		search_keyword='';
	}
	var params={'current_page':current_page,'search_tab_name':search_tab_name,'destination':destination
	,'search_keyword':search_keyword,'date_checkin':date_checkin,'date_checkout':date_checkout
	,'product_id':product_id,'product_name':product_name,'search_position_index':search_position_index,'is_ad':is_ad
	,'ad_source':ad_source};
	
	//alert(JSON.stringify(params));
	gatherInfoBySensors('HotelSearchResultClick',params);
}

//酒店发送搜索请求
function hotelSendSearchReq(current_page,destination,search_keyword,date_checkin,date_checkout,hot_keyword,module_name,history_keyword,search_result,relevance_keyword,is_filter,filter_type,filter_first_category,filter_second_category){
	
	var params={'current_page':current_page,'destination':destination,'search_keyword':search_keyword
	,'date_checkin':date_checkin,'date_checkout':date_checkout,'hot_keyword':hot_keyword
	,'module_name':module_name,'history_keyword':history_keyword,'search_result':search_result
	,'relevance_keyword':relevance_keyword,'is_filter':is_filter,'filter_type':filter_type
	,'filter_first_category':filter_first_category,'filter_second_category':filter_second_category};
	
	gatherInfoBySensors('HotelSendSearchReq',params);
}

//商品坑位点击(完成)
function productClick(current_page,module_name,product_id,product_name,product_first_category,product_second_category,product_price,product_tab){
	current_page=getNameByCode(current_page);
	product_first_category=getNameByCategoryId(product_first_category);
	product_second_category=getNameByCategoryId(product_second_category);
	var params={'current_page':current_page,'module_name':module_name
	,'product_id':product_id,'product_name':product_name,'product_first_category':product_first_category
	,'product_second_category':product_second_category,'product_price':product_price,'product_tab':product_tab};
	
	gatherInfoBySensors('ProductClick',params);
}

//模块按钮点击 TAB页切换(完成)
function moduleClick(current_page,module_name,button_name,button_index){
	current_page='公共搜索列表页';
	module_name='公共搜索tab点击';
	moduleClick2(current_page, module_name, button_name, button_index);
}

//写这个方法是因为与之前的业务冲突，但是之前的调用点多改动风险大，所以做个兼容
function moduleClick2(current_page,module_name,button_name,button_index){
	
	var params={'current_page':current_page,'module_name':module_name,'button_name':button_name,'button_index':button_index};
	//alert("current_page="+current_page+",module_name="+module_name+",button_name="+button_name+",button_index="+button_index);
	gatherInfoBySensors('ModuleClick',params);
}

//点击搜索产品(除酒店外)(完成)
function searchResultClick(current_page,tab_name,keyword,product_id,product_name,product_first_category,product_second_category,commodity_id,commodity_name,position_index,is_ad,ad_source){
	
	if(is_ad=="1"){
		is_ad=true;
		if((tab_name=="ticket" || tab_name=="local" || tab_name=="group" || tab_name=="scenictour" || tab_name=="freetour") && ad_source=="1"){
			ad_source="大数据推荐（优选标签）";
			
		}else{
			ad_source="后台配置（推荐标签）";
		}
		
	}else{
		is_ad=false;
	}
	
	current_page='搜索列表';
	tab_name=getNameByCode(tab_name);
	product_first_category=getNameByCategoryId(product_first_category);
	product_second_category=getNameByCategoryId(product_second_category);
	var params={'current_page':current_page,'tab_name':tab_name,'keyword':keyword,'product_id':product_id
	,'product_name':product_name,'product_first_category':product_first_category,'product_second_category':product_second_category
	,'commodity_id':commodity_id,'commodity_name':commodity_name,'position_index':position_index,'is_ad':is_ad,'ad_source':ad_source};
	
	gatherInfoBySensors('SearchResultClick',params);
	
}

//发送搜索请求(除酒店外)
function sendSearchReq(current_page,tab_name,keyword,hot_keyword,module_name,history_keyword,search_result,relevance_keyword,is_filter,filter_type,filter_first_category,filter_second_category){

	var params={'current_page':current_page,'tab_name':tab_name,'keyword':keyword,'hot_keyword':hot_keyword
	,'module_name':module_name,'history_keyword':history_keyword,'search_result':search_result
	,'relevance_keyword':relevance_keyword,'is_filter':is_filter,'filter_type':filter_type
	,'filter_first_category':filter_first_category,'filter_second_category':filter_second_category}
	
	gatherInfoBySensors('SendSearchReq',params);
}

//通过编号获取中文名称
function getNameByCode(code){
	if("hotel"==code){
		return "酒店";
	}else if("ticket"==code){
		return "门票";
	}else if("ship"==code){
		return "邮轮";
	}else if("visa"==code){
		return "签证";
	}else if("localplay"==code){
		return "当地玩乐";
	}else if("route"==code){
		return "全部旅游";
	}else if("local"==code){
		return "当地游";
	}else if("group"==code){
		return "跟团游";
	}else if("scenictour"==code){
		return "酒景";
	}else if("freetour"==code){
		return "自由行";
	}else{
		return code;
	}
}

/**
 *根据品类id获取名称 
 * @param categoryId
 */
function getNameByCategoryId(categoryId){
	if("1"==categoryId){
		return "酒店";
	}else if("11"==categoryId){
		return "门票";
	}else if("12"==categoryId){
		return "其它票";
	}else if("8"==categoryId){
		return "邮轮";
	}else if("4"==categoryId){
		return "签证";
	}else if("31"==categoryId){
		return "演出票";
	}else if("41"==categoryId){
		return "交通接驳";
	}else if("43"==categoryId){
		return "美食";
	}else if("44"==categoryId){
		return "娱乐";
	}else if("45"==categoryId){
		return "购物";
	}else if("28"==categoryId){
		return "WIFI/电话卡";
	}else if("15"==categoryId){
		return "跟团游";
	}else if("16"==categoryId){
		return "当地游";
	}else if("17"==categoryId){
		return "酒店套餐";
	}else if("18"==categoryId){
		return "自由行";
	}else if("181"==categoryId){
		return "酒景";
	}else if("182"==categoryId){
		return "机酒";
	}else if("183"==categoryId){
		return "交通服务";
	}else if("185"==categoryId){
		return "机票+当地游";
	}else if("186"==categoryId){
		return "机票+门票";
	}else if("187"==categoryId){
		return "机票+X";
	}else{
		return categoryId;
	}
	
	
}

//刷新发送事件  收集数据
function sendSensorsDataForRefresh(){
	
	//神策需要的数据
	var currentPage="";//当前页编号比如hotel
	var destination="";//行政区
	var searchKeyword="";//关键词
	var startDate="";
	var endDate="";
	var hotKeyword=false;//是否使用热词
	var moduleName="";//使用热词模块名称
	var historyKeyword=false;//是否使用历史词
	var searchResult=0;//总条数
	var isRelevance=false;//是否补全
	var isFilter=false;//是否筛选
	var filterType="";//筛选类型
	var filterFirstCategory="";
	var filterSecondCategory="";
	
	try{
		currentPage=getCurrentPage();
		searchKeyword=exposuredKeyword;
		if(searchKeyword==""){
			searchKeyword=$("#js_keyword").val();
		}
		
		
		var filterArr=analysisFilter(currentPage);
		isFilter=filterArr[0];
		filterType=filterArr[1];
		filterFirstCategory=filterArr[2];
		filterSecondCategory=filterArr[3];
		
		//取结果数-页签统计数据
		searchResult=getSearchResult(currentPage);
		
		//获取补全标志
		var isUseCompletion=$("span.btn_lv_search").attr("is_use_completion");
		if(isUseCompletion=="true"){
			isRelevance=true;
		}
		//神策埋点 
		if("hotel"==currentPage){
			//入住时间
			startDate = $("#startDate").val();
			endDate = $("#endDate").val();
			//var jsKeyword = $("#js_keyword");
			//destination = jsKeyword.attr("data-id");
			destination = $("#js_destination").val();
			
			currentPage=getNameByCode(currentPage);
			if('酒店名/商圈/地标'==searchKeyword){
				searchKeyword='';
			}
			hotelSendSearchReq(currentPage,destination,searchKeyword,startDate,endDate,hotKeyword,moduleName,historyKeyword,searchResult,isRelevance,isFilter,filterType,filterFirstCategory,filterSecondCategory);
		}else{
			var tabName=getNameByCode(currentPage);
			currentPage='搜索列表';
			sendSearchReq(currentPage,tabName,searchKeyword,hotKeyword,moduleName,historyKeyword,searchResult,isRelevance,isFilter,filterType,filterFirstCategory,filterSecondCategory);
		}
	}catch(e){
		//console.log("error "+e);
	}	
}

//根据url判断是哪个搜索列表
function getCurrentPage(){
	var currentPage='';
	
	var url = window.location.href;
	var url1=url.replace("http://s.lvmama.com/", '');
	var url2=url1.replace("http://www.lvmama.com/", '');
	currentPage=url2.substring(0,url2.indexOf("/"));
	
	if(currentPage!='hotel' && currentPage!='youlun' && currentPage!='visa' 
		&& currentPage!='ticket' && currentPage!='route' && currentPage!='freetour'
			&& currentPage!='scenictour' && currentPage!='group' && currentPage!='localplay'
				&& currentPage!='local'){
		if(url2.indexOf("hotel")!=-1){
			currentPage= "hotel";
		}else if(url2.indexOf("youlun")!=-1){
			currentPage= "youlun";
		}else if(url2.indexOf("visa")!=-1){
			currentPage= "visa";
		}else if(url2.indexOf("ticket")!=-1){
			currentPage= "ticket";
		}else if(url2.indexOf("route")!=-1){
			currentPage= "route";
		}else if(url2.indexOf("freetour")!=-1){
			currentPage= "freetour";
		}else if(url2.indexOf("scenictour")!=-1){
			currentPage= "scenictour";
		}else if(url2.indexOf("group")!=-1){
			currentPage= "group";
		}else if(url2.indexOf("localplay")!=-1){
			currentPage= "localplay";
		}else if(url2.indexOf("local")!=-1){
			currentPage= "local";
		}
	}
	return currentPage;
}

//获取总条数
function getSearchResult(currentPage){
	var searchResult=0;
	if("route"==currentPage){
		searchResult=allRouteItemCount;
	}else if("freetour"==currentPage){
		searchResult=allFreetourItemCount;
	}else if("scenictour"==currentPage){
		searchResult=allScenictourItemCount;
	}else if("group"==currentPage){
		searchResult=allGroupItemCount;
	}else if("local"==currentPage){
		searchResult=allLocalItemCount;
	}else{
		searchResult=allItemCount;
	}
	return searchResult;
}

//解析筛选项
function analysisFilter(type){
	var items = "";
	
	if("hotel"==type){
		items=[[hotelPositionFilterS,"酒店位置"],[hotelSubjectFilterM,"类别"],[hotelStarFilterM,"星级"]
		,[hotelBrandFilterM,"品牌"],[hotelPriceFilterS,"房价"],[hotelFacilitiesFilterM,"设施服务"]
		,[hotelPromotionFilterM,"优惠"],[hotelScoreFilterS,"评分"],[bedTypeS,"床型"],[breakfastTypeS,"早餐类型"],[payTypeS,"支付方式"],[sortFilter,"排序"],[screenFilter,"筛选"]];
	}else if("youlun"==type){
		items=[[shipLineFilterM,"邮轮航线"],[shipDistrictFilterM,"出发地"],[shipBrandFilterS,"邮轮公司"]
		,[shipMonthFilterM,"开航日期"],[shipForeignFlagFilterS,"上船港口"],[sortFilter,"排序"],[screenFilter,"筛选"]];
	}else if("visa"==type){
		items=[[visaTypeIdFilterS,"签证类型"],[visaRangeIdFilterS,"所属领区"],[sortFilter,"排序"],[screenFilter,"筛选"]];
	}else if("ticket"==type){
		items=[[ticketProvinceFilterS,"省目的地"],[ticketCityFilterS,"城市目的地"],[ticketCountyFilterS,"区县目的地"]
		,[ticketSubjectFilterS,"主题"],[sortFilter,"排序"],[screenFilter,"筛选"]];
	}else if("route"==type ||"freetour"==type ||"scenictour"==type || "group"==type || "local"==type){
		items=[[routeCategoryIdFilter,"产品类型"],[routePlayMethodFilter,"线路玩法"],[routeRouteNumFilter,"游玩天数"]
		,[routeStartYearMonthFilter,"出发时间"],[routeDistrictIdFilter,"出发城市"],[routeProductGradeFilter,"产品等级"]
		,[routeCrowdTagIdFilter,"适用人群"],[routeBrandTagIdFilter,"自主品牌"],[routeSubjectIdFilter,"线路主题"]
		,[routeProductTypeFilter,"是否出境"],[routeCategoryFilter,"产品类型"],[routeHotelStarFilter,"酒店等级"]
		,[routeHotelBrandIdFilter,"酒店品牌"],[routeDestIdFilter,"目的地"],[routeViewPiontFilter,"游玩景点"]
		,[routeGroupTypeFilter,"产品类型"],[routeTrafficFilter,"交通工具"],[routePromotionTypesFilter,"优惠"]
		,[sortFilter,"排序"],[screenFilter,"筛选"]];
	}else if("localplay"==type){
		items=[[localplayProductTypeFilter,"区域"],[localplayDestinationFilter,"目的地"],[localplayPlayMethodTypeIdsFilter,"玩法分类"]
		,[localplaySubjectIdFilter,"玩乐主题"],[sortFilter,"排序"],[screenFilter,"筛选"]];
	}else{
		var result=new Array('','','','');
		return result; 
	}
	
	return joinItems(items);
}

//拼接筛选项
function joinItems(items){
	var isFilter='';
	var filterType='';
	var filterFirstCategory="";
	var filterSecondCategory="";
	
	for ( var i = 0; i <items.length; i++){
		var item=items[i];
		if(item[0]!=''){
			if(filterFirstCategory!=''){
				filterFirstCategory=filterFirstCategory+"/";
				filterSecondCategory=filterSecondCategory+"/";
			}
			filterFirstCategory=filterFirstCategory+item[1];
			filterSecondCategory=filterSecondCategory+item[0];
		}
	}
	
	if(filterFirstCategory!=''){
		isFilter=true;
		var arrTmp1=filterSecondCategory.split("/");
		var arrTmp2=filterSecondCategory.split(",");
		if(arrTmp1.length>1 || arrTmp2.length>1){
			filterType='多选';
		}else{
			filterType='单选';
		}
		
	}else{
		isFilter=false;
	}
	
	var result=new Array(isFilter,filterType,filterFirstCategory,filterSecondCategory);
	return result; 
}